// const {queryAll} = require('../../database/dbUtils');
import JwtAuth from "../../middleware/jwt";
import { queryAll } from "../../database/dbUtils";
import { Context } from "koa";
const {query} = require("koa/lib/request");
export const login = async (ctx:any) => { //async router.get('路径',async (ctx)=>)
  const {username, password} = ctx.request.body;
  const token = JwtAuth.signUserToken({username});
  const sql = `select username from user where username="${username}"`;
  const res:any = await queryAll(sql);
  if (res.length !== 0) {
    const sql = `select * from user where username="${username}" AND password="${password}"`;
    const res:any = await queryAll(sql);
    console.log(res);
    if (res.length !== 0) {
      ctx.status = 200;
      ctx.body = {
        code: 200,
        token,
        msg: '登录成功',
        username,
        uid: res[0].uid,
        loginTime: new Date().getTime()
      };
    } else {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        msg: '密码错误'
      };
    }
  } else {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      msg: '用户名错误'
    };
  }

};

export const registry = async (ctx:Context) => {


  // 201 已创建
  // 插入到数据库
  ctx.status = 201;//400
  // 用户名和密码
  const {username, password, age, name} = ctx.request.body;
  // 如果数据库里面存在 代表注册失败  如果数据库不存在 注册成功
  const sql = `select username from user where username="${username}"`;
  const res:any = await queryAll(sql);
  if (res.length !== 0) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      msg: '该账号已被注册'
    };
    return;
  }
  let sqlRegistry = `insert into user (username,password`;
  age && (sqlRegistry += ',age');
  name && (sqlRegistry += ',name');
  sqlRegistry += ')';
  sqlRegistry += ` values ("${username}","${password}"`;
  age && (sqlRegistry += `,"${age}"`);
  name && (sqlRegistry += `,"${name}"`);
  sqlRegistry += ')';
  const insertRes = await queryAll(sqlRegistry);
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  if (insertRes.protocol41) {
    ctx.body = {
      code: 200,
      msg: '注册成功'
    };
  } else {
    ctx.body = {
      code: 500,
      msg: '注册失败'
    };
  }
};
// user/:id
export const getUser = async function (ctx:any) {

  // 验签
  const userInfo = JwtAuth.verifyUserToken(ctx.header.authorization);
  console.log(userInfo);
  const {id} = ctx.params;
  ctx.status = 200;
  const sql = `select username,uid,name,age from user where uid=${id}`;
  const resUserInfo:any = await queryAll(sql);
  ctx.body = {...resUserInfo[0]};
};
